package com.liyghting.txtsplit;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.OutputStream;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author LiYiGuang
 * @date 2021/1/8 15:37
 */
public class TxtSplitSwing {
	public static void main(String[] args) throws Exception {
		final JFrame jf = new JFrame("日志分割工具窗口");
		jf.setSize(400, 250);
		jf.setLocationRelativeTo(null);
		jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

		JPanel panel = new JPanel();

		// 创建文本区域, 用于显示相关信息
		final JTextArea msgTextArea = new JTextArea(10, 30);
		msgTextArea.setLineWrap(true);
		panel.add(msgTextArea);

		JButton openBtn = new JButton("打开");
		openBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				showFileOpenDialog(jf, msgTextArea);
			}
		});
		panel.add(openBtn);

		JButton saveBtn = new JButton("分割");
		saveBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					showFileSaveDialog(jf, msgTextArea);
				} catch (Exception exception) {
					exception.printStackTrace();
					msgTextArea.setText("切割异常" + exception.getMessage());
				}
			}
		});
		panel.add(saveBtn);

		jf.setContentPane(panel);
		jf.setVisible(true);
	}

	/*
	 * 打开文件
	 */
	private static void showFileOpenDialog(Component parent, JTextArea msgTextArea) {

		msgTextArea.setText(null);
		// 创建一个默认的文件选取器
		JFileChooser fileChooser = new JFileChooser();

		// 设置默认显示的文件夹为当前文件夹
		fileChooser.setCurrentDirectory(new File("D:\\user\\01370744\\Downloads"));

		// 设置文件选择的模式（只选文件、只选文件夹、文件和文件均可选）
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		// 设置是否允许多选
		fileChooser.setMultiSelectionEnabled(false);

		// 添加可用的文件过滤器（FileNameExtensionFilter 的第一个参数是描述, 后面是需要过滤的文件扩展名 可变参数）
		// fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("zip(*.zip,
		// *.rar)", "zip", "rar"));
		// 设置默认使用的文件过滤器
		fileChooser.setFileFilter(new FileNameExtensionFilter("txt(*.txt, *.log)", "txt", "log"));

		// 打开文件选择框（线程将被阻塞, 直到选择框被关闭）
		int result = fileChooser.showOpenDialog(parent);

		if (result == JFileChooser.APPROVE_OPTION) {
			// 如果点击了"确定", 则获取选择的文件路径
			File file = fileChooser.getSelectedFile();

			// 如果允许选择多个文件, 则通过下面方法获取选择的所有文件
			// File[] files = fileChooser.getSelectedFiles();

			msgTextArea.append("打开文件: " + file.getAbsolutePath());
		}
	}

	/*
	 * 选择文件保存路径
	 */
	private static void showFileSaveDialog(Component parent, JTextArea msgTextArea) throws Exception {

		String txtPath = msgTextArea.getText().substring(6);
		Path path = Paths.get(txtPath);
		long currentTimeMillis = System.currentTimeMillis();
		long houserend = 1024L * 1024 * 100;
		byte[] bytes = Files.readAllBytes(path);
		FileSystem fileSystem = path.getFileSystem();
		String separator = fileSystem.getSeparator();
		int lastIndexOf = txtPath.lastIndexOf(separator);
		String dir = txtPath.substring(0, lastIndexOf);
		String lastFile = txtPath.substring(lastIndexOf + 1, txtPath.lastIndexOf("."));
		String smallFile = dir + separator + currentTimeMillis + lastFile + "_1.txt";
		msgTextArea.append("\n" + "切割输出文件开始");
		msgTextArea.append("\n" + smallFile);
		Path smallPath = Paths.get(smallFile);
		Files.createFile(smallPath);
		OutputStream outputStream = Files.newOutputStream(smallPath);
		byte[] temp = new byte[4096];
		int length = 4096;
		int writedSize = 0;
		int writedFileCount = 1;
		for (int i = 0; i < bytes.length;) {
			if (i + 4096 > bytes.length) {
				length = bytes.length - i;
				temp = new byte[length];
			}
			System.arraycopy(bytes, i, temp, 0, length);
			outputStream.write(temp);
			writedSize = writedSize + length;
			if (writedSize > houserend) {
				writedFileCount++;
				smallFile = dir + separator + currentTimeMillis + lastFile +"_"+ writedFileCount + ".txt";
				msgTextArea.append("\n" + smallFile);
				smallPath = Paths.get(smallFile);
				Files.createFile(smallPath);
				outputStream = Files.newOutputStream(smallPath);
				writedSize = 0;
			}
			if (i + 4096 > bytes.length) {
				break;
			} else {
				i = i + 4096;
			}

		}
		msgTextArea.append("\n" + "切割输出文件结束，cost：" + (System.currentTimeMillis() - currentTimeMillis) / 1000 + "秒");
	}
}
